<!-- AreaManagement.vue -->
<template>
  <div>
    <h2 style="margin-bottom: 15px">区域管理</h2>
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="省">
        <el-select @change="cityQuery" v-model="queryForm.province" placeholder="请选择省">
          <el-option
            v-for="item in provinces"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市">
        <el-select v-model="queryForm.city" placeholder="请选择市">
          <el-option
            v-for="item in cities"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区域名称">
        <el-input v-model="queryForm.name" placeholder="请输入区域名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery" class="query-button">查询</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        <el-button type="success" @click="handleAdd">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-if="tableData.length > 0"
      @selection-change="handleSelectionChange"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="province" label="省"></el-table-column>
      <el-table-column prop="city" label="市"></el-table-column>
      <el-table-column prop="name" label="区域名称"></el-table-column>
      <el-table-column prop="communityCount" label="小区数量"></el-table-column>
      <el-table-column prop="remarks" label="备注"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button-group>
            <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="tableData.length > 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <div v-else style="text-align: center; margin-top: 20px;">
      <el-empty description="暂无数据，请先进行查询"></el-empty>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="添加区域">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="省市区" class="full-width" prop="region">
          <el-cascader
            v-model="form.region"
            :options="regionData"
            placeholder="请选择省市区"
            style="width: 100%;"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="editDialogVisible" title="修改区域">
      <el-form :model="editForm" :rules="editRules" ref="editForm">
        <el-form-item label="区域id" prop="id">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="省" class="full-width" prop="province">
          <el-select
            @change="editCityQuery"
            v-model="editForm.province"
            style="width: 100%;"
            placeholder="请选择省"
          >
            <el-option
              v-for="item in provinces"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市" class="full-width" prop="city">
          <el-select v-model="editForm.city" style="width: 100%;" placeholder="请选择市">
            <el-option
              v-for="item in editCities"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入区域名称"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remarks" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { regionData } from "element-china-area-data";

export default {
  data() {
    return {
      dialogVisible: false,
      editDialogVisible: false,
      form: {
        region: [],
        remark: ""
      },
      editForm: {
        id: "",
        province: "",
        city: "",
        name: "",
        remarks: ""
      },
      queryForm: {
        province: "",
        city: "",
        name: ""
      },
      provinces: [],
      cities: [],
      editCities: [],
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: "",
      regionData: this.formatRegionData(regionData),
      rules: {
        region: [
          { required: true, message: "请选择省市区", trigger: "blur" },
          {
            type: "array",
            required: true,
            message: "请选择省市区",
            trigger: "change"
          }
        ]
      },
      editRules: {
        id: [{ required: true, message: "区域id不能为空", trigger: "blur" }],
        province: [{ required: true, message: "请选择省", trigger: "blur" }],
        city: [{ required: true, message: "请选择市", trigger: "blur" }],
        name: [
          { required: true, message: "请输入区域名称", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
            message: "区域名称只能包含中文或英文字符",
            trigger: "blur"
          }
        ],
        selectedRows: []
      }
    };
  },
  mounted() {
    this.provinceQuery();
    this.handleQuery();
  },
  methods: {
    formatRegionData(data) {
      return data.map(province => ({
        value: province.value,
        label: province.label,
        children: province.children.map(city => ({
          value: city.value,
          label: city.label,
          children: city.children.map(district => ({
            value: district.value,
            label: district.label
          }))
        }))
      }));
    },
    provinceQuery() {
      this.$axios.post("area/province", { none: "none" }).then(res => {
        if (res.data.code === 200) {
          this.provinces = [];
          res.data.data.forEach(province => {
            this.provinces.push({ value: province.name, label: province.name });
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    cityQuery() {
      this.queryForm.city = "";
      this.$axios
        .post("area/city", { province: this.queryForm.province })
        .then(res => {
          if (res.data.code === 200) {
            this.cities = [];
            res.data.data.forEach(city => {
              this.cities.push({ value: city.name, label: city.name });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.handleQuery();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.handleQuery();
    },
    handleQuery() {
      let curr =
        this.queryForm.name == "" ? (this.currentPage - 1) * this.pageSize : 0;
      this.$axios
        .post("area/query", {
          ...this.queryForm,
          size: this.pageSize,
          curr
        })
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success("查询成功");
            this.tableData = res.data.data;
            this.total = res.data.total;
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    editCityQuery() {
      this.editForm.city = "";
      this.$axios
        .post("area/city", { province: this.editForm.province })
        .then(res => {
          if (res.data.code === 200) {
            this.editCities = [];
            res.data.data.forEach(city => {
              this.editCities.push({ value: city.name, label: city.name });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要删除的区域");
        return;
      }
      this.$confirm("确定要删除选中的区域吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios.post("area/delete", this.selectedRows).then(res => {
            if (res.data.code === 200) {
              this.$message.info(this.data.success);
              this.handleQuery();
            } else {
              this.$message.error(res.data.message);
            }
          });
        })
        .catch(() => {});
    },
    handleAdd() {
      this.dialogVisible = true;
      this.form = {
        region: [],
        areaName: "",
        remark: ""
      };
    },
    handleEdit(row) {
      this.editDialogVisible = true;
      this.editForm = { ...row };
      this.editCityQuery();
    },
    handleSave() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const [provinceCode, cityCode, areaCode] = this.form.region;
          const province = this.regionData.find(p => p.value === provinceCode);
          const city = province.children.find(c => c.value === cityCode);
          const area = city.children.find(a => a.value === areaCode);
          if (province && city && area) {
            this.$axios
              .post("area/add", {
                province: province.label,
                city: city.label,
                name: area.label,
                remarks: this.form.remark
              })
              .then(res => {
                if (res.data.code === 200) {
                  this.$message.success("地区添加成功");
                  this.dialogVisible = false;
                  if (city.label === this.queryForm.city) {
                    this.handleQuery();
                  }
                } else {
                  this.$message.error(res.data.message);
                }
              })
              .catch(err => {
                this.$message.error(err);
              });
          } else {
            this.$message.error("地区名称转换失败");
          }
          this.dialogVisible = false;
        } else {
          this.$message.error("请填写完整信息");
          return false;
        }
      });
    },
    handleUpdate() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm("确定要修改吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.$axios
                .post("area/update", this.editForm)
                .then(res => {
                  if (res.data.code === 200) {
                    this.$message.success("地区更新成功");
                    this.editDialogVisible = false;
                    this.handleQuery();
                  } else {
                    this.$message.error(res.data.message);
                  }
                })
                .catch(err => {
                  this.$message.error(err.message);
                });
            })
            .catch(() => {});
        } else {
          return false;
        }
      });
    },
    handleDelete(index, row) {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("area/delete", [row])
            .then(res => {
              if (res.data.code === 200) {
                this.$message.info(res.data.message);
                this.handleQuery();
              }
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    }
  }
};
</script>

<style scoped>
.query-button {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}
.demo-form-inline .el-form-item {
  margin-right: 10px;
}
</style>
